package com.xbjtech.vipsystem.controller;

import com.github.pagehelper.PageInfo;
import com.xbjtech.vipsystem.po.Role;
import com.xbjtech.vipsystem.service.RoleService;
import com.xbjtech.vipsystem.utils.ArgumentResolver;
import com.xbjtech.vipsystem.vo.Result;
import com.xbjtech.vipsystem.vo.RoleOptVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author leejun.happy@gmail.com
 * @created 2019-07-26
 *
 * 角色接口
 * list
 * add
 * edit
 * delete
 * 给角色分配权限的接口
 *
 *
 */
@RestController
@RequestMapping("/role")
@Slf4j
@Api
public class RoleController {

    @Autowired
    RoleService roleService;

    @ApiOperation(value = "获取列表分页数据")
    @GetMapping("/data")
    public Map<String, Object> data(
            @RequestParam(value = "roleName", required = false)
            String roleName,
            @RequestParam(value = "roleCode", required = false)
            String roleCode,
            @RequestParam(value = "page", required = false, defaultValue = "1")
            int page,
            @RequestParam(value = "limit", required = false, defaultValue = "10")
            int limit) {
        Example ex = new Example(Role.class);
        ex.setOrderByClause("id desc");
        Example.Criteria criteria = ex.createCriteria();
        if (null != roleName && roleName.length() != 0) {
            criteria.andLike("roleName", "%" + roleName + "%");
        }
        if (null != roleCode && roleCode.length() != 0) {
            criteria.andLike("roleCode", "%" + roleCode + "%");
        }

        PageInfo<Role> rolePageInfo = roleService.selectByExamplePage(page, limit, ex);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", rolePageInfo.getTotal());
        map.put("data", rolePageInfo.getList());
        return map;
    }

    @GetMapping("/get/{id}")
    public Role get(@PathVariable Integer id) {
        return roleService.selectByPrimaryKey(id);
    }

    @PostMapping("/save")
    public Result<String> save(@RequestBody Role role) {
        try {
            if (role.getId() == null) {
                // 新增操作
                roleService.insertWithoutPrimaryKey(role);
            } else {
                // 修改操作
                Role basic = roleService.selectByPrimaryKey(role.getId());
                ArgumentResolver<Role> resolver = new ArgumentResolver<>();
                Role result = resolver.resolver(basic, role, Role.class);
                roleService.updateByPrimaryKey(result);
            }
            return Result.ok("保存成功");
        } catch (Exception e) {
            log.error("{}", e.getMessage());
        }
        return Result.fail("保存失败");
    }

    /**
     * restful
     *        查  get        /role/1
     *        改  put        /role
     *        增  post       /role
     *        删  delete     /role/1
     * @return
     */
    @ApiOperation(value = "通过id删除角色信息")
    @GetMapping("/remove/{id}")
    public Result<String> delete(@PathVariable Integer id) {
        try {
            roleService.deleteByPrimaryKey(id);
            return Result.ok("删除成功");
        } catch (Exception e) {
            log.error("delete()方法发生异常：{}", e.getMessage());
        }
        return Result.fail("删除失败");
    }


    /**
     * POST
     * 先确定好发什么类型的POST请求
     * application/json
     *      [
     *          {roleId:1, resId:2},
     *          {roleId:1, resId:3},
     *      ]
     * application/x-www-form-urlencoded
     * Post => GET :/res/opt?roleId=1&resIds=1&resIds=2...
     *
     * @return
     */
    @ApiOperation(value = "给特定某一个角色分配权限")
    @PostMapping("/opt")
    public Result<String> opt(@RequestBody RoleOptVO[] vos) {
        // 知道到底现在给哪个角色在分配权限
        // 分配的又是哪些权限
        // 入库
        try {
            // vos 长度是3
            // for 循环会遍历3次
            // 会执行3条insert语句
            // 这3条insert语句有不可被分割的特征
            // 要么同时成功，要么同时失败
            // 解决方案，3条insert语句要执行在一个事务内
            long begin = System.currentTimeMillis();
            roleService.insertRoleAndResRelation(vos);
            long end = System.currentTimeMillis();
            System.out.println(end - begin);

            return Result.ok("分配成功");
        } catch (Exception e) {
            log.error("{}", e.getMessage());
        }
        return Result.fail("分配失败");
    }

    @GetMapping("/selectResByRoleId/{id}")
    public List<Integer> selectResByRoleId(@PathVariable Integer id) {
        return roleService.selectResByRoleId(id);
    }

    @GetMapping("/selectAllRoles")
    public List<Role> selectAllRoles() {
        return roleService.selectAll();
    }

}
